package org.anachronos.jeep.agent;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.AttributeChangeNotification;
import javax.management.NotificationBroadcasterSupport;

import org.anachronos.jeep.core.trace.TraceModelBuilder;
import org.anachronos.jeep.core.trace.impl.Trace;

public class ProfilerControl extends NotificationBroadcasterSupport 
	implements ProfilerControlMBean {
	
	private static Logger logger = Logger.getLogger(ProfilerControl.class.getName());
	
	private Trace trace;

	private int classesToProcess;

	private int processedClasses;

	private long sequenceNumber;
	
	@Override
	public void save(final String fileName) {
		try {
			TraceModelBuilder.save(trace, fileName);
		} catch (Exception e) {
			logger.log(Level.SEVERE, "", e);
		}
	}

	@Override
	public void startProfiling() {
		trace = TraceModelBuilder.startProfiling();
	}

	@Override
	public void stopProfiling() {
		TraceModelBuilder.stopProfiling();
	}

	
	public void setClassesToProcess(final int classesToProcess) {
		final int oldValue = this.classesToProcess;
		this.classesToProcess = classesToProcess;
		attributeChanged("classesToProcess", oldValue, classesToProcess);
	}

	public void setProcessedClasses(final int processedClasses) {
		final int oldValue = this.processedClasses;
		this.processedClasses = processedClasses;
		attributeChanged("processedClasses", oldValue , classesToProcess);
	}

	public int getClassesToProcess() {
		return classesToProcess;
	}

	public int getProcessedClasses() {
		return processedClasses;
	}
	
	private void attributeChanged(final String attributeName, final int oldValue, final int newValue) {
		final AttributeChangeNotification changeNotification = new AttributeChangeNotification(this, 
				sequenceNumber++, System.currentTimeMillis(), 
				null, attributeName, Integer.class.getSimpleName()
				, oldValue, newValue);
		sendNotification(changeNotification);
	}
}
